package com.treasure.service.collocate.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.treasure.service.BaseService;
import com.treasure.service.collocate.service.ArticleService;
import com.treasure.service.commons.lang.util.BeanUtil;
import com.treasure.service.commons.lang.util.IdCreater;
import com.treasure.service.commons.lang.util.StringUtil;
import com.treasure.service.domain.TArticle;
import com.treasure.service.domain.TArticleExample;
import com.treasure.service.dto.TArticleDto;
import com.treasure.service.mapper.TArticleMapper;
import com.treasure.service.result.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 银行或渠道商配置信息
 *
 * @author <a href="mailto:panxinwen@yingu.com">Pan Xinwen</a>
 * @version 1.0 2018-10-30 11:06
 */
@Service
public class ArticleServiceImpl extends BaseService implements ArticleService {

    @Autowired
    private TArticleMapper articleMapper;

    @Override
    public PageResult<List<TArticleDto>> getArticleList(Integer pageSize, Integer pageNum, Integer status,Integer recommend) {

        Page page = PageHelper.startPage(pageNum,pageSize);

        TArticleExample example = new TArticleExample();
        TArticleExample.Criteria criteria = example.createCriteria();
        if (!StringUtil.isEmpty(status)){
            criteria.andStatusEqualTo(status);
        }

        if (!StringUtil.isEmpty(recommend)){
            criteria.andRecommendEqualTo(recommend);
        }

        example.setOrderByClause("create_time desc");

        List<TArticle> list = articleMapper.selectByExample(example);

        List<TArticleDto> result = new ArrayList<>();

        if (list != null){

            list.forEach(tArticle -> {
                TArticleDto tArticleDto = BeanUtil.copy(tArticle,TArticleDto::new);
                tArticleDto.setContent("");
                result.add(tArticleDto);

            });

        }

        return new PageResult(page,result);
    }

    @Override
    public Integer updateArticle(TArticle tArticle) {
        if (StringUtil.isEmpty(tArticle.getId())){
            tArticle.setId(IdCreater.getLongId());
            return articleMapper.insert(tArticle);
        }else {
            return articleMapper.updateByPrimaryKeySelective(tArticle);
        }
    }

    @Override
    public TArticleDto getArticleInfo(TArticle tArticle) {

        return BeanUtil.copy(articleMapper.selectByPrimaryKey(tArticle.getId()),TArticleDto::new);
    }
}
